<template>
  <!-- 企业信息完善 -->
  <div class="app-container-add">
    <el-row v-if="activeName==='first'" :gutter="10" class="button-wrap" :style="{width:mainContentWidth + 'px','left':'80px'}">
      <el-col :span="1.5">
        <el-button v-clickForbidden icon="el-icon-document-checked" size="middle" :disabled="isBtnDisa" @click="handleSave">保存</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button v-clickForbidden icon="el-icon-document" size="middle" :disabled="isBtnDisa" @click="handleMaterial">企业资料</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button v-clickForbidden icon="el-icon-document" size="middle" :disabled="isBtnDisa" @click="handleEnterpriseFiling">企业备案</el-button>
      </el-col>
    </el-row>
    <div class="main-content">
      <el-card ref="mainContent" class="box-card" shadow="never">
        <div class="main-content-body">
          <el-form ref="formData" class="data-form" :model="formData" label-width="80px">
            <div class="data-form-item">
              <div class="two-level-title">基本信息</div>
              <el-row>
                <el-col :span="8">
                  <el-form-item label="企业名称" prop="name">
                    <el-input v-model="formData.name" readonly />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="企业类型" prop="sysEnterpriseType">
                    <el-select :value="formData.sysEnterpriseType" readonly placeholder="" style="width: 100%">
                      <el-option
                        v-for="item in enterTypeOptions"
                        :key="item.typeNum"
                        :label="item.typeName"
                        :value="item.typeNum"
                      />

                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="信用代码" prop="creditCodePic">
                    <el-input v-model="formData.creditCodePic" readonly />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="单位法人" prop="legalperson">
                    <el-input v-model="formData.legalperson" readonly />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="详细地址" prop="address">
                    <el-input v-model="formData.address" readonly />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="成立日期" prop="establishmentTime ">
                    <el-date-picker
                      v-model="formData.establishmentTime"
                      value-format="yyyy-MM-dd"
                      style="width:100%"
                      type="date"
                      placeholder=""
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="企业等级" prop="qualificationLevel">
                    <el-select v-model="formData.qualificationLevel" style="width: 100%" placeholder="">
                      <el-option
                        v-for="item in proGrade"
                        :key="item.dictValue"
                        :label="item.dictLabel"
                        :value="item.dictValue"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="" prop="userdName">
                    <label slot="label" v-html="`曾&ensp;用&ensp;名`" />
                    <el-input v-model="formData.userdName" />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="" prop="contacts">
                    <label slot="label" v-html="`联&ensp;系&ensp;人`" />
                    <el-input v-model="formData.contacts" />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="联系电话" prop="phone">
                    <el-input v-model="formData.phone" />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="企业账号" prop="loginName">
                    <el-input v-model="formData.loginName" readonly />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="企业类别" prop="foreignCompany">
                    <el-radio-group v-model="formData.foreignCompany" size="medium">
                      <el-radio label="1">本地企业</el-radio>
                      <el-radio label="0">外地企业</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-col>
                <el-col>
                  <el-form-item label="营业执照" prop="unitCreditCodePicUrl">
                    <ImgUploadOne
                      ref="fileUplode"
                      :edit-file-list="businessLicensePicList"
                      @getFilePic="getbusinessLicensePic"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              <div class="two-level-title">经营范围</div>
              <div class="certificate-wrap">
                <div v-for="(item,index) in titleList" :key="index" class="certi-item">
                  <h3 class="certi-titile">{{ item.businessName }}</h3>
                  <el-row>
                    <el-checkbox-group v-model="CheckBusinessData[index]" @change="handleChange()">
                      <el-checkbox v-for="(i,ind) in item.children" :key="ind" :checked="i.flag" :label="i">{{ i.businessName }}</el-checkbox>
                    </el-checkbox-group>
                  </el-row>
                </div>
              </div>
              <!--证件信息-->
              <el-row>
                <certificateList ref="certificateList" :fixed-certificate="{...formData}" :sys-enterprise-type="formData.sysEnterpriseType" :add-cert-list="addCertList" :cert-list.sync="certList" edit="1" title="证件信息" @updateFixed="updateFixed" />
              </el-row>
            </div>
          </el-form>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script>
import { changeCertificate } from '@/api/register'
import { mapState } from 'vuex'
import { editEnterprise, detailEnterprise } from '@/api/system/enterpriseInfo'
// 地区接口
import { listByTreeProcessType } from '@/api/common/area.js'
// 证件列表
import certificateList from '@/components/certificateList/enterprise'
// 页面组件- 附件上传
import ImgUploadOne from '@/components/Upload/ImgUploadOne'
import { listNoPermission } from '@/api/superviseBaseInfo/typeManage/organizationType'
export default {
  name: 'CompanyInfo',
  components: {
    ImgUploadOne,
    certificateList
  },
  data() {
    return {
      mainContentWidth: '',
      isBtnDisa: false,
      status: '',
      activeName: 'first',
      // 生成证书
      addCertList: [],
      // 证书信息
      certList: [],
      // 企业类型
      enterTypeOptions: [],
      // 城市列表
      cityOptions: [],
      typeOptions: [
        { value: '0', label: '企业备案' }
      ],
      /* 图片上传 start*/
      businessLicensePicList: [], // 上传的营业执照
      filingList: [], // 上传备案资料
      /* 图片上传 end*/
      /* 信息 start */
      filingData: { // 新增数据
        recordType: '',
        recordStartDate: '',
        recordEndDate: '',
        proRecordList: '',
        address: '',
        recordExplain: '',
        appFiles: ''
      },
      formData: {
        id: '',
        establishmentTime: '', // 成立日期
        qualificationLevel: '', // 企业等级
        name: '', // 企业名称
        userdName: '', // 曾用名
        sysEnterpriseType: '', // 企业性质
        legalperson: '', // 单位法人
        creditCodePic: '', // 信用代码
        address: '', // 详细地址
        contacts: '', // 联系人
        phone: '', // 联系电话
        loginName: '', // 账号
        foreignCompany: '',
        businessScope: [], // 选择的经营范围
        certificateNum: '', // 证书编号
        unitCreditCodePicUrl: '', // 营业执照
        qualificationUrl: '' // 固定证书
      },
      titleList: '', // 企业经营范围标题
      CheckBusinessData: [] // 选择的经营范围二维数组
      /* 信息 end */
    }
  },
  computed: {
    ...mapState({
      userId: state => state.user.userInfo.userId,
      proGrade: state => state.basicInfo.proGrade
    })
  },
  mounted() {
    /** 获取主题内容宽度 start*/
    setTimeout(() => {
      this.mainContentWidth = this.$refs.mainContent.$el.offsetWidth
    }, 500)
    const that = this
    window.onresize = () => {
      return (() => {
        that.mainContentWidth = that.$refs.mainContent.$el.offsetWidth
      })()
    }
    /** 获取主题内容宽度 end*/
    this.getDetailById() // 获取企业详情
    this.getRegionTree() // 获取区域树
    this.getSupperType()
  },
  methods: {
    // 修改固定证书
    updateFixed(val) {
      const { certificateNum, validUntil, qualificationLevel, qualificationUrl } = val
      this.formData = { ...this.formData, certificateNum, validUntil, qualificationLevel, qualificationUrl }
    },
    // 获取生成证书的数据
    async getCertList(typeNum) {
      const { data } = await changeCertificate({ typeFlag: '1', typeNum })
      this.addCertList = data
    },
    // 获取企业类型
    async getSupperType() {
      const query = { typeVal: 1 }
      const { data: { rows }} = await listNoPermission(query)
      this.enterTypeOptions = rows
    },
    // 获取详情
    async getDetailById() {
      const { data } = await detailEnterprise()
      if (data) {
        const { sysEnterprise, record, record: { appFiles, nation, region, province, city, county }, businessScope, enterpriseCertificate } = data
        this.formData = { ...sysEnterprise }
        this.certList = enterpriseCertificate
        if (sysEnterprise && sysEnterprise.id) { this.filingData = { ...record, enterpriseId: sysEnterprise.id } }
        this.filingData.proRecordList = [nation, region, province, city, county]
        this.titleList = businessScope
        if (appFiles) {
          this.filingList = appFiles
        }
        if (sysEnterprise && sysEnterprise.unitCreditCodePicUrl) {
          this.businessLicensePicList = sysEnterprise.unitCreditCodePicUrl.split(',').map(fileId => ({ fileId }))
        }
        this.CheckBusinessData = this.titleList.map((item) => {
          return []
        })
        // 根据企业类型生成证书
        if (sysEnterprise && sysEnterprise.sysEnterpriseType) this.getCertList(sysEnterprise.sysEnterpriseType)
      }
    },
    // 选择地区后拆分5个字段
    handleRegion(regionList) {
      const [nation, region, province, city, county] = regionList
      this.filingData = { ...this.filingData, nation, region, province, city, county }
    },
    // 获取区域树
    getRegionTree() {
      listByTreeProcessType({ regionCode: '' }).then((res) => {
        if (res) {
          this.cityOptions = this.deleteChildren(res.data.rows)
        }
      })
    },
    // 更新数据
    async handleSave() {
      if (this.$refs.certificateList.isEditCert) {
        this.msgWarning('请先保存正在编辑的证书!')
        return
      }
      this.isBtnDisa = true
      const { formData, formData: { businessScope }, filingData } = this

      const saveCertList = this.$refs.certificateList.cloneCertList.map((item) => {
        const { id, certificateId, certificateVal, certificateName, fileId } = item
        return { id, fileId, certificateId, certificateName, certificateVal: JSON.stringify(certificateVal) }
      })
      const { code } = await editEnterprise({
        ...formData,
        proRecord: JSON.stringify(filingData),
        businessScopeJson: JSON.stringify(businessScope),
        certificateJson: saveCertList
      })
      if (code === 200) {
        this.msgSuccess('保存成功!')
        this.getDetailById()
      }
      this.isBtnDisa = false
    },
    // 选择经营范围
    handleChange() {
      this.formData.businessScope = []
      this.CheckBusinessData.forEach(item => {
        item.forEach(value => {
          // const { businessName, parentId, ancestor } = value
          this.formData.businessScope.push({ businessId: value.id, enterpriseId: this.formData.id })
        })
      })
    },
    // 动态经营范围降维
    flattenDeep(arr1) {
      return arr1.reduce((acc, val) => Array.isArray(val) ? acc.concat(this.flattenDeep(val)) : acc.concat(val), [])
    },
    /** ************ 文件上传 start *******************/
    // 营业执照
    getbusinessLicensePic(fileList) {
      this.formData.unitCreditCodePicUrl = fileList[0].fileId
    },
    // 备案资料
    getFiling(fileList) {
      this.filingData.appFiles = fileList
    },
    /** ************ 文件上传end *******************/
    // 跳转企业资料
    handleMaterial() {
      this.$router.push({
        path: 'enterpriseMaterial'
      })
    },
    // 企业备案
    handleEnterpriseFiling() {
      this.$router.push({
        path: '/system/enterprise-filing'
      })
    }
  }
}
</script>

<style lang='scss' scoped>
  .certificate-wrap {
    .certi-item {
      margin-bottom: 20px;
      border-radius: 4px;
      padding: 5px 20px;
      box-sizing: border-box;
      border: 1px solid #e0d7d7;
      .certi-titile {
        font-size: 16px;
        line-height: 36px;
        margin:0 0 15px;
        text-align: left;
        border-bottom: 1px solid #e0d7d7;
        color: #1890ff;
      }
      .certi-ipt-wrap {
        display: flex;
        justify-content: space-around;
      }
    }
    .el-form-item {
      display: block;
    }
    .el-checkbox {
      margin-bottom: 10px;
      font-weight: normal;
    }
  }
</style>
